package com.eastfair.es;

import com.alibaba.fastjson.JSONObject;
import com.eastfair.core.plumelog.CompressMessage;
import com.eastfair.core.plumelog.RunLogMessage;
import com.eastfair.es.dao.AllLogDao;
import com.eastfair.es.entity.AllLog;
import com.eastfair.plumelog.util.LZ4Util;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class RedisMessageListener implements MessageListener {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    AllLogDao allLogDao;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取消息
        byte[] messageBody = message.getBody();
        // 使用值序列化器转换
        Object msg = redisTemplate.getValueSerializer().deserialize(messageBody);
        CompressMessage compressMessage = (CompressMessage) msg;
        List<String> messageList = LZ4Util.decompressorMessage(compressMessage);
        // 获取监听的频道
        byte[] channelByte = message.getChannel();
        // 使用字符串序列化器转换
        Object channel = redisTemplate.getStringSerializer().deserialize(channelByte);
        // 渠道名称转换
        String patternStr = new String(pattern);
//        System.out.println(patternStr);
//        System.out.println("---频道---: " + channel);
//        System.out.println("---消息内容---: " + JSONObject.toJSONString(messageList));
        List<AllLog> allLogList = new ArrayList<>();
        for (String messageStr : messageList) {
            RunLogMessage runLogMessage = JSONObject.parseObject(messageStr, RunLogMessage.class);
            AllLog allLog = new AllLog();
            BeanUtils.copyProperties(runLogMessage, allLog);
            allLogList.add(allLog);
        }
        Long l = System.currentTimeMillis();
        allLogDao.batchSave(allLogList);
//        String s = String.format("插入条数：%s , 耗时：%s", allLogList.size(), (System.currentTimeMillis() - l));
//        System.out.println(s);
    }
}
